import APIS from '@/apis';
import URLS from '@/apis/APIUrlDefine';
import Const from '@/common/Const';
import request from '@/utils/request';
import {PlusOutlined} from '@ant-design/icons';
import {Upload, Button, Popover, Input, List, Space, Divider} from 'antd';

import {RcCustomRequestOptions} from 'antd/lib/upload/interface';
// import { urlencoded } from 'express';
import React, {useEffect, useState} from 'react';
import './index.css';
// import { data } from 'jquery';

const ImageUpload: React.FC<any> = (props) => {
  const [showAddButton, updateAddButton] = useState(props.preImage ? false : true);
  const [showSelectModal, updateSelectModal] = useState(false);
  const [lastSelect, updateLastSelect] = useState<any>(null);
  const [lastSelectImage, updateLastSelectImage] = useState<any>(null);
  // const [imageUrl, SetImageUrl] = useState(props.preImage);
  const [assetData, updateAssetData] = useState<any>({
    data: [],
    total: 0,
    pageSize: 10,
    current: 0,
  });

  const [fileList, updateFileList] = props.preImage
    ? useState<any>([
      {
        uid: Date.now(),
        percent: 100,
        url: URLS.SERVER_PICTURE_URL + props.preImage,
        status: 'done',
      },
    ])
    : useState<any>([]);

  // SetImageUrl(props.preImage);

  useEffect(() => {
    if (fileList.length > 0 && fileList[0].url && fileList[0].url.endsWith(props.preImage)) {
      return;
    }
    if (props.preImage) {
      updateFileList([
        {
          uid: Date.now(),
          percent: 100,
          url: URLS.SERVER_PICTURE_URL + props.preImage,
          status: 'done',
        },
      ]);
      updateAddButton(false);
    }
  },props?.des);

  //自定义上传方法
  const customRequestUpload = async (option: RcCustomRequestOptions) => {
    var data = new FormData();
    updateFileList([
      {
        uid: option.file.uid,
        percent: 99,
        status: 'uploading',
      },
    ]);
    data.append('filename', option.file);
    data.append('type', '1');
    var result = await request('/api/utils/v1/upload', {
      method: 'POST',
      data: data,
    }).catch((ex) => {
    });
    if (result) {
      var asset = await APIS.AssetAPI.CreateNewAsset({
        url: result.data,
        type: Const.ASSET_TYPE.IMAGE_TYPE,
      }).catch(() => {
      });
      updateFileList([
        {
          uid: option.file.uid,
          percent: 100,
          url: URLS.SERVER_PICTURE_URL + asset.data?.url,
          status: asset.data ? 'done' : 'error',
        },
      ]);
      props.handleImageChange?.(result.data);
    }
  };

  const renderSelectPopup = () => (
    <div style={{}}>
      <Input.Search placeholder="请输入搜索的图片"></Input.Search>
      <Divider></Divider>
      <List
        style={{width: '700px'}}
        dataSource={assetData.data}
        pagination={{
          current: assetData.current,
          total: assetData.total,
          pageSize: 8,
          onChange: async (page, count) => {
            var result = await APIS.AssetAPI.GetAssetList({current: page, pageSize: count}, 1);
            updateAssetData(result);
          },
        }}
        grid={{
          gutter: 1,
          xs: 2,
          sm: 3,
          md: 4,
          lg: 4,
          xl: 4,
          xxl: 4,
        }}
        footer={
          <Space>
            <Button
              disabled={!lastSelect}
              onClick={async () => {
                updateSelectModal(false);
                updateFileList([
                  {
                    uid: Date.now() + '',
                    url: URLS.SERVER_PICTURE_URL + lastSelectImage.url,
                    status: 'done',
                  },
                ]);
                updateAddButton(false);
                props.handleImageChange?.(lastSelectImage.url);

              }}
            >
              确定
            </Button>
            <Button onClick={() => {
              updateSelectModal(false);
            }}>取消</Button>
          </Space>
        }
        renderItem={(item: any, index) => (
          <div key={index} className="image-card">
            <img
              alt="example"
              src={URLS.SERVER_PICTURE_URL + item.url}
              onClick={(event) => {
                var img = event.target as HTMLImageElement;
                if (lastSelect) {
                  lastSelect.parentElement?.classList.remove('ant-card-body-img-select');
                }
                updateLastSelect(img);

                updateLastSelectImage(item);
                img.parentElement?.classList.add('ant-card-body-img-select');
              }}
            />
            <div
              className="image-title"
              style={{
                // position: ,
                top: '-30px',
                width: '100%',
                height: '30px',
                backgroundColor: 'rgba(0,0,0,0.4)',
              }}
            >
              <span>测试图片</span>
            </div>
          </div>
        )}
      >
      </List>
    </div>
  );
  return (
    <div style={{display: 'flex'}}>
      <Upload
        accept=".jpg,.png"
        className="uplaod-image-btn"
        showUploadList={{showPreviewIcon: true, showRemoveIcon: true}}
        multiple={false}
        name="logo"
        action="/upload.do"
        onRemove={(remove) => {
          updateAddButton(true);
          updateFileList([]);
          props.handleImageChange?.(null);
        }}
        fileList={fileList}
        customRequest={customRequestUpload}
        onChange={({fileList}) => {
          updateAddButton(fileList.length === 0);
          updateFileList(fileList);
        }}
        listType="picture-card"
      >
        {showAddButton ? <Button icon={<PlusOutlined/>}></Button> : null}
      </Upload>
      <Popover
        content={renderSelectPopup}
        title="请选择一个图片"
        trigger="click"
        visible={showSelectModal}
        onVisibleChange={(visible) => updateSelectModal(visible)}
      >
        <Button
          onClick={async () => {
            updateSelectModal(true);
            var result = await APIS.AssetAPI.GetAssetList(
              {current: 1, pageSize: 8},
              1,
            ).catch(() => {
            });

            updateAssetData(result);
          }}
          style={{height: '104px', width: '104px', padding: '0px 0px'}}
        >
          从列表中选取
        </Button>
      </Popover>
    </div>
  );
};

export default ImageUpload;
